package com.lagou.rpc.provider.zookeeperRegister;


import com.lagou.rpc.provider.client.WatcherApi;
import com.lagou.rpc.provider.client.ZkApi;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ZookeeperRegister implements register {

    @Autowired
    ZkApi api;
    @Override
    public void register(String path, String address,String port) {
          //是否存在节点 "/register/server/
        Stat exists = api.exists("/server", true);
        if(exists == null ){
            api.createNode("/server","");
        }
        //创建临时节点
        api.createLinShiNode("/server/"+address+":"+port,address+":"+port);

    }

    public List<String> discovery(String path){
        ArrayList<String> strings = new ArrayList<>();
        WatcherApi watcherApi = new WatcherApi();
        try {
            List<String> children =
                    api.getChildren(path);

            for(String chil:  children){
                String data = api.getData(chil, watcherApi);
                strings.add(data);
            }

        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return strings;
    }

}
